package two.chapter_3.c3_4;

import two.chapter_1.c1_3.LinkedQueue;
import two.chapter_1.c1_3.Queue;
import two.chapter_3.c3_1.SequentialSearchST;

public class SeparateChainingHashST<Key,Value> implements HashST<Key,Value> {
    private SequentialSearchST<Key,Value>[] sts;
    private int M;
    public SeparateChainingHashST(){
        this(997);
    }
    public SeparateChainingHashST(int capacity){
        this.M=capacity;
        sts=new SequentialSearchST[capacity];
        for (int i=0;i<sts.length;i++){
            sts[i]=new SequentialSearchST<>();
        }
    }


    @Override
    public void put(Key key, Value value) {
        sts[hash(key)].put(key,value);

    }

    @Override
    public Value get(Key key) {
        return sts[hash(key)].get(key);
    }

    @Override
    public void delete(Key key) {

    }

    @Override
    public Iterable<Key> keys() {
        Queue<Key> queue=new LinkedQueue<>();
        for (int i=0;i<sts.length;i++){
            for (Key key:sts[i].keys()){
                queue.enqueue(key);
            }
        }

        return queue;
    }

    @Override
    public boolean contains(Key key) {
        return get(key)!=null;
    }

    @Override
    public int hash(Key key){
        return (key.hashCode() & 0x7fffffff)%M;
    }

    @Override
    public boolean isEmpty() {
        return size()==0;
    }

    @Override
    public int size() {
        int size=0;
        for (int i=0;i<sts.length;i++){
            size+=sts[i].size();
        }
        return size;
    }
}
